// 引入axios
import axios from "axios";
//引入query string
import qs from "querystring"
axios.defaults.baseURL = '/api/';

import router from "@/router";

//设置请求拦截拦截器
axios.interceptors.request.use((req) => {
    //判断除了登陆以外的所有路由
    if (req.url != "/userlogin") {
        //登陆的时候携带请求头
        req.headers.authorization = sessionStorage.getItem("userinfo")
            ? JSON.parse(sessionStorage.getItem("userinfo")).token
            : null
    }
    return req
})

// 设置响应拦截
axios.interceptors.response.use((res) => {
    // 全局设置token过期和token拦截
    if (res.data.msg == "请设置请求头,并携带验证字符串") {
        alert(res.data.msg)
        router.push('/login')
    } else if (res.data.msg == "登录已过期或访问权限受限") {
        alert(res.data.msg)
        router.push('/login')
    } else {
        return res.data
    }


})


//封装get方法
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
//封装post方法
export const post = (url, params = {}, isFile = false) => {
    let data = {}
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qs.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
